package chat.aylan.top.service;
/*
 * @Author Abduahad
 * @Description 服务端线程
 * @Date 2019-01-10
 */
import chat.aylan.top.CloseUtil;
import chat.aylan.top.Main;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;

public class ServerThread implements Runnable, Serializable {

    private User user;
    private DataInputStream dis;
    private DataOutputStream dos;
    private boolean isAlive = true;


    public ServerThread(Socket socket){
        try {
            dis = new DataInputStream(socket.getInputStream());
            dos = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
              System.out.println("bug");
        }
    }

    /**
     * 处理所有类型的消息发生
     * @param message
     */
    private void sendToEveryone(String message){
        if(null != message && !message.equals("")){
            JSONObject json = JSONObject.parseObject(message);
            String msg = json.getString("message");
            if(json.getInteger("type") == 2){
                if(null != msg && !msg.equals("")){
                   for (ServerThread thread:Main.list){
                       if(json.getInteger("toUserId") == thread.user.getId()){
                           Information information = new Information(2);
                           information.put("message",msg);
                           information.put("user",json.getObject("user",User.class));
                           send(JSON.toJSONString(information),thread);
                       }
                   }
                }
            }else if (json.getInteger("type") == 1){
                this.user = json.getObject("user",User.class);
                System.out.println("user connected "+json.getJSONObject("user").getString("username"));

                // 给自己通知在线人list
                if(Main.list.size() > 0){
                    Information information = new Information(4);
                    send(JSON.toJSONString(information),this);
                }

                // 给大家通知自己上线
                publish(message);

            }else if(json.getInteger("type") == 5){
                // 群聊
                publish(message);
            }
        }
    }

    /**
     * 发布所有人的
     * @param message
     */
    private void publish(String message){
        for (ServerThread server : Main.list){
            if(server != this){
                send(message,server);
            }
        }
    }

    /**
     * 发送一个人
     * @param msg
     * @param from
     */
    private void send(String msg, ServerThread from){
        try {
            from.dos.writeUTF(msg);
            from.dos.flush();
        } catch (IOException e) {
            die(from);
        }
    }

    /**
     * 监听
     * @return
     */
    private String listen(){
        String msg = "";
        try {
            msg = dis.readUTF();
            System.out.println("receive " + msg);
        } catch (IOException e) {
            die(this);
        }
        return msg;
    }

    @Override
    public void run() {
        while (isAlive){
            sendToEveryone(listen());
        }
    }

    /**
     * 处理出现故障的线程
     * @param server
     */
    private void die(ServerThread server){
        isAlive = false;
        // 通知大家某人下线
        Information information = new Information(3);
        information.put("data",server.user);
        publish(JSONObject.toJSONString(information));

        // 处理下线事情
        if(null != server){
            CloseUtil.closeAll(server.dis,server.dos);
            Main.list.remove(server);
        }
        System.out.println("some one gone his id "+server.user.getId());

    }

}
